from artSightWorld.apps.base.models import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import random, math
from django.db.models import Q, Count

def getPhotoComments(request, idPhoto, displayAll):
	photo = Photo.objects.get(id=idPhoto);
	return render_to_response('displayPhoto/listCommentaires.html', { 'photoContent':photo, 'displayAll':int(displayAll) }, context_instance=RequestContext(request) )

	
def getPhotoResize(photo):
	widthMax = 750
	heightMax = 400
	newWidth = photo.width 
	newHeight = photo.height
	ratio = float(photo.height)/float(photo.width)
	if( photo.width > widthMax) :
		newWidth = widthMax
		newHeight = round(newWidth * ratio)
	if( photo.width < photo.height and photo.height > heightMax ) :	
		newHeight = heightMax
		newWidth = round(newHeight / ratio)
	photo.newWidth = newWidth
	photo.newHeight = newHeight
	photo.miniHeight = int(math.ceil(170*(float(photo.height) / float(photo.width))))
	photo.urlThumb = str(photo.image).replace("original", "thumb")
	
# Create an array of columns. Each cell contains a list of photo source
def createPhotoCols(photos,nbPhotoToDisplay):
	cols = ["","","","",""]
	colsHeight = {}
	for i in range(5):
		colsHeight[i] = 0
		cols[i] = []
	for photo in photos:
		indexMinCol = getMinCol(colsHeight)
		getPhotoResize(photo)
		colsHeight[indexMinCol] += photo.miniHeight + 20
		cols[indexMinCol].append(photo)
	return cols
	
def createFakePhoto():
	firstPhoto = Photo()
	firstPhoto.image = "images/fakePhoto.jpg"
	firstPhoto.height = 100
	firstPhoto.width = 170
	return firstPhoto

# Create an array of columns. Each cell contains a list of photo source
def createAlbumCols(albums,nbPhotoToDisplay):
	cols = ["","","","",""]
	colsHeight = {}
	for i in range(5):
		colsHeight[i] = 0
		cols[i] = []
	for album in albums:
		indexMinCol = getMinCol(colsHeight)
		photos = Photo.objects.filter(album__id=album.id)
		if len(photos)>0:
			album.firstPhoto = photos[0]
		else :
			album.firstPhoto = createFakePhoto()
		getPhotoResize(album.firstPhoto)
		colsHeight[indexMinCol] += album.firstPhoto.height + 20
		cols[indexMinCol].append(album)
	return cols

# return the index of the columns with the smalest height
def getMinCol(colsHeight):
	minColIndex = 0
	minColValue = colsHeight[0]
	for i in range(1,5):
		if minColValue > colsHeight[i] :
			minColValue = colsHeight[i] 
			minColIndex = i
	return minColIndex

def getDataPagination( datas , nbPhotoPerPage, numPage ):
	paginator = Paginator(datas, nbPhotoPerPage)
	try:
		pages = paginator.page(numPage)
	except PageNotAnInteger:
		pages = paginator.page(1)
	except EmptyPage:
		pages = paginator.page(paginator.num_pages)
	return pages

def displayLast(request, nbPhotoToDisplay, numPage):
	photos = Photo.objects.all().order_by('-datePosted')
	pages = getDataPagination(photos, int(nbPhotoToDisplay), int(numPage))
	cols = createPhotoCols(pages.object_list,int(nbPhotoToDisplay))
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response('displayPhoto/photos.html', {'gridType':'displayLast', 'photoType':'photos_recentes', 'myPhotographer':myPhotographer, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1) }, context_instance=RequestContext(request) )


def displayLastPopular(request, nbPhotoToDisplay, numPage):
	photos=Photo.objects.annotate(nbLiked=Count("photosLiked")).order_by('-nbLiked')
	pages = getDataPagination(photos, int(nbPhotoToDisplay), int(numPage))
	cols = createPhotoCols(pages.object_list,int(nbPhotoToDisplay))
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response('displayPhoto/photos.html', {'gridType':'displayLastPopular', 'photoType':'photos', 'myPhotographer':myPhotographer, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1) }, context_instance=RequestContext(request) )

def displayLastFollowed(request, photographeFollowing, nbPhotoToDisplay, numPage):
	photographer = Photographer.objects.get(user__id=photographeFollowing)
	followed = photographer.photographersLiked.all()
	photos = []
	for pFollowed in followed :
		photoFollowed = Photo.objects.filter(album__photographer__id=pFollowed.user.pk)
		for photo in photoFollowed:
			photos.append(photo)

	pages = getDataPagination(photos, int(nbPhotoToDisplay), int(numPage))
	cols = createPhotoCols(pages.object_list,int(nbPhotoToDisplay))
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response('displayPhoto/photos.html', {'gridType':'displayLastFollowed/'+photographeFollowing, 'photoType':'photos_followed', 'myPhotographer':myPhotographer, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1) }, context_instance=RequestContext(request) )


def displayFollowedList(request, photographeFollowing):
	photographer = Photographer.objects.get(user__id=photographeFollowing)
	followed = photographer.photographersLiked.all()

	for follow in followed :
		photos=Photo.objects.filter(album__photographer__pk=follow.user.id)
		cnt = len(photos)
		if (cnt>0):
			follow.photo1=Photo.objects.filter(album__photographer__pk=follow.pk).order_by('-datePosted')[0].image
			if (cnt>1):
				follow.photo2=Photo.objects.filter(album__photographer__pk=follow.pk).order_by('-datePosted')[1].image
				if(cnt>2):
					follow.photo3=Photo.objects.filter(album__photographer__pk=follow.pk).order_by('-datePosted')[2].image
					if (cnt>3):
						follow.photo4=Photo.objects.filter(album__photographer__pk=follow.pk).order_by('-datePosted')[3].image
					else:
						follow.photo4=""
				else :
					follow.photo3=""
					follow.photo4=""
			else:
				follow.photo2=""
				follow.photo3=""
				follow.photo4=""
		else :
			follow.photo1=""
			follow.photo2=""
			follow.photo3=""
			follow.photo4=""
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response('displayPhoto/photographerFollowedList.html', {'photographers':followed, 'myPhotographer':myPhotographer}, context_instance=RequestContext(request) )

def displayFavorites(request, photographeLiking, nbPhotoToDisplay, numPage):
	photographer = Photographer.objects.get(user__id=photographeLiking)
	photosLiked = photographer.photosLiked.all()

	pages = getDataPagination(photosLiked, int(nbPhotoToDisplay), int(numPage))
	cols = createPhotoCols(pages.object_list,int(nbPhotoToDisplay))
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response('displayPhoto/photos.html', {'gridType':'displayFavorites/'+photographeLiking, 'photoType':'photos_fav', 'myPhotographer':myPhotographer, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1) }, context_instance=RequestContext(request) )

	
def getAllAlbumOfPhotographer( idPhotographer ):
	#albums = []
	#for albumsID in Photo.objects.values('album_id').filter(photographer__id=idPhotographer).distinct():
	#	albums.append( Album.objects.get(id=albumsID['album_id']) )

	albums = Album.objects.filter(photographer__id = idPhotographer)
	return albums
	
def displayAlbumsList(request, idPhotographer, nbPhotoToDisplay, numPage, myProfil = 0):	
	datas = getAllAlbumOfPhotographer(idPhotographer)
	pages = getDataPagination(datas, int(nbPhotoToDisplay), int(numPage))
	cols = createAlbumCols(pages.object_list,int(nbPhotoToDisplay))
	if (myProfil != 0) :
		myProfil = 1
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response("displayPhoto/albums.html", {'gridType':'displayAlbumsList/'+idPhotographer, 'photoType':'photos_album', 'myPhotographer':myPhotographer, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1), 'myProfile':myProfil }, context_instance=RequestContext(request) )

def displayAlbumPhoto(request, idPhotographer, idAlbum, nbPhotoToDisplay, numPage, myProfil = 0):
	# if idAlbum = 0 we display the list of albums of the photographer / if it's any other number, we display the list of photos of this specific album
	datas = Photo.objects.filter(album__id=idAlbum)
	pages = getDataPagination(datas, int(nbPhotoToDisplay), int(numPage))
	cols = createPhotoCols(pages.object_list,int(nbPhotoToDisplay))
	urlRetour = "displayAlbumsList/"+idPhotographer+"/20/1/"
	if (request.user.is_authenticated()):
		myPhotographer = Photographer.objects.get(user__id=request.user.pk);
	else :
		myPhotographer = 0
	return render_to_response("displayPhoto/photos.html", {'gridType':'displayAlbumPhoto/'+idPhotographer+'/'+idAlbum, 'photoType':'photos_album', 'myPhotographer':myPhotographer, 'albumId':idAlbum, 'columns':cols, 'pages':pages, 'nbPages':range(1,pages.paginator.num_pages+1), 'urlRetour':urlRetour, 'myProfile':myProfil}, context_instance=RequestContext(request) )

	
	